﻿using System;
using System.Collections.Generic;
using System.Linq;

using SharedGenomics.Core;
using SharedGenomics.Domain;
using SharedGenomics.Annotations;

namespace SharedGenomics.Workbench.Annotations
{
    public class SnpAnnotationRepository
    {
        private readonly IDictionary<string, AnnotationInfoSet> _snpAnnotations;

        public SnpAnnotationRepository(IEnumerable<AnalysisResult> results, IEnumerable<AnnotationDescriptor> annotationDescriptors)
        {
            //get all snp names in the result set
            var resultSetSnps = (results ?? Enumerable.Empty<AnalysisResult>())
                .SelectMany(result => result.GetSnpPropertyValues());

            //set will remove any duplicates (case-insensitive)
            HashSet<string> uniqueSnps = new HashSet<string>(resultSetSnps, StringComparer.InvariantCultureIgnoreCase);

            //create annotation map - each snp should have a corresponding annotation set. This set depends on the active annotations in the annotation manager
            //get all active annotation descriptors
            List<AnnotationDescriptor> descriptorList = (annotationDescriptors ?? Enumerable.Empty<AnnotationDescriptor>()).ToList();

            //create dictionary - each annotation set should have a root SnpName value
            this._snpAnnotations = uniqueSnps
                .ToDictionary(snp => snp, snp => new AnnotationInfoSet(new AnnotationValue(AnnotationKey.SnpName, snp), descriptorList), StringComparer.InvariantCultureIgnoreCase); 
        }

        public AnnotationInfoSet this[string snpName]
        {
            get
            {
                return snpName == null ? null : this._snpAnnotations.GetValueWithDefault(snpName);
            }
        }

        public IEnumerable<AnnotationInfoSet> AnnotationSets
        {
            get { return this._snpAnnotations.Values.ToArray(); }
        }
    }
}
